package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.Md5Utils;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Shine
 * @description：
 * @date ：2021/2/24 10:37
 */
@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        //业务逻辑：1.调用服务层方法，2.生成一个token方便返回前端和存入Redis，3.将数据存入Redis

        String token = UUID.randomUUID().toString().replaceAll("-", "");
        UserInfo info = userService.login(userInfo);

        if (info != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("nickName", info.getNickName());

            JSONObject userJson = new JSONObject();
            userJson.put("userId", info.getId().toString());
            userJson.put("ip", IpUtil.getIpAddress(request));

            //将登陆数据存入redis
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token, userJson.toJSONString(), RedisConst.USERKEY_TIMEOUT , TimeUnit.SECONDS);

            return Result.ok(map);
        } else {
            return Result.fail().message("用户登录失败，请重试！");
        }
    }

    @GetMapping("logout")
    public Result logout(HttpServletRequest request) {
        //    删除Redis中的数据,head中只是拿到了token
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX + request.getHeader("token"));
        return Result.ok();


    }
}
